<?php

namespace App\Http\Controllers\Admin\Integral;

use App\Http\Controllers\Controller;
use App\Models\Integrallog;
use App\Models\SystemConfig;
use App\Traits\Controllers\IndexTraits;
use App\Transformers\IntegralLogUserTransFormer;
use Illuminate\Http\Request;

class IntegralLogController extends Controller
{
    //显示用户
    use IndexTraits;

    //使用积分日志的模型
    public $model = Integrallog::class;

    //使用积分日志的transformer
    public $transformer = IntegralLogUserTransFormer::class;

    //获取积分配置信息
    public function integralAllocation()
    {
        //查询所有的积分配置的信息
        $integral = SystemConfig::where('category_name', 'ji-fen-pei-zhi')->get()->toArray();

        foreach ($integral as $k => $v) {
            if ($v['menu_name'] === 'integral_effective_time') {
                $array = explode(' ', $v['parameter']);
                //便利得到的数组
                foreach ($array as $a) {
                    $arr[] = explode('=>', $a);
                    foreach ($arr as $b => $c) {
                        $arr1[$b]['value'] = $c[0];
                        $arr1[$b]['label'] = $c[1];
                    }
                }
                $integral[$k]['parameter'] = $arr1;
            }
        }
        //将查询到的数据进行返回
        return $this->response->array($integral);
    }

    //修改积分配置的路由
    public function updateIntegral(Request $request)
    {
        $res = $request->all();  //获取表单传来的数据
        $integral = SystemConfig::where('category_name', 'ji-fen-pei-zhi')->get(); //查询所有的内容
        //通过循环将获取到的数据进行更改保存
        for ($a = 0; $a < count($integral); $a++) {
            foreach ($res as $k => $v) {
                if ($integral[$a]['menu_name'] == $k) {
                    $integral[$a]['value'] = $v;
                    $integral[$a]->save();  //将更改后的模型进行保存
                }
            }
        }
        return $this->response->noContent();
    }

    //显示列表
    public function index(Request $request)
    {
        //先处理传过来的搜索数据
        $this->formatIndexQuery($request);
        //查询积分日志的列表
        $data = $this->getQuery()
            ->pimp()//自动转换where条件
            ->with('user:id,nickname')  //使用模型关联进行查询用户对应的用户的信息
            ->paginate($this->getPageLimit());  //进行分页处理
        return $this->response->paginator($data, resolve($this->transformer));
    }

    //统计签到次数和积分的数量
    public function integral_sum()
    {
        //统计积分总和的查询条件
        $nums = $this->getQuery()
            //统计积分
            ->selectRaw("SUM(front_integral) as integral_num,
            COUNT(IF(title = 'sign',id,0)) as signs,
            SUM(IF(title = 'sign',get_points,0)) as signs_integral,
            SUM(IF(type = 0,get_points,0)) as use_num")
            ->get()->toArray();
        return $this->response->array($nums[0]);
    }

}
